package cn.hhchat.kit.date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

/**
 * Created this one by HMH on 2017/3/21.
 */
public class DateUtil {

    static final Logger logger = LoggerFactory.getLogger(DateUtil.class);


    public static Date StringLinuxTimeStamp2Date(String datestr) {
        DateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));

        Date date = null;
        try {
            date = format.parse(datestr);
        } catch (ParseException e) {
            logger.error("转换Linux时间失败\n",e);
            return new Date(0);
        }
        return date;
    }

    /**
     * 转换时间
     * @param date 日期
     * @param time 时间
     * @param pattern 模式
     * @return Date时间
     */
    public static Date String2Date(String date, String time, String pattern) {
        SimpleDateFormat dateFormat;
        if (pattern == null) {
            dateFormat = new SimpleDateFormat("yyyy-MM-dd hhchat:mm");
        }else {
            dateFormat = new SimpleDateFormat(pattern);
        }
        String strDate = date + " " + time;
        Date result=null;
        try {
            result = dateFormat.parse(strDate);
        } catch (ParseException e) {
            logger.error("转换时间失败\n",e);
        }
        return result;
    }

    public static Date String2Date(String date, String pattern) {
        SimpleDateFormat dateFormat;
        if (pattern == null) {
            dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        }else {
            dateFormat = new SimpleDateFormat(pattern);
        }
        Date result=null;
        try {
            result = dateFormat.parse(date);
        } catch (ParseException e) {
            logger.error("转换时间失败\n",e);
        }
        return result;
    }

    public static String date2String(Date date) {
        return date2String(date, "yyyy-MM-dd HH:mm");
    }

    public static String date2String(Date date, String pattern) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        return simpleDateFormat.format(date);
    }




    public static Timestamp getTimeStampNow() {
        return new Timestamp(new Date().getTime());
    }
}
